package com.atues.thread.syn;

public class UnsafeBuyTicket {

    public static void main(String[] args) {
        // 创建一个买票的线程
        BuyTicket buyTicket = new BuyTicket();
        Thread thread1 = new Thread(buyTicket, "小明");
        Thread thread2 = new Thread(buyTicket, "小蓝");
        Thread thread3 = new Thread(buyTicket, "小红");

        // 启动线程
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class  BuyTicket implements Runnable{
//    private  int ticket = 10;
    private volatile int ticket = 10;
    private boolean flag = true; // true表示正在售票，false表示停止售票
    @Override
    public void run(){
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    //对方法进行上锁；锁==队列排队+阻塞，如果进入了同步代码，那么其他线程就不能进入了
    private synchronized void  buy() throws InterruptedException {
        //
        if(ticket <=0){
            flag = false; // 停止售票
            return;
        }
        // 模拟网络延迟
        Thread.sleep(200);
        System.out.println(Thread.currentThread().getName() + "买票，票号：" + ticket);
        ticket--;
    }
}
